import {
	is_oss_upload,
	baseUrl
} from '@/sheep/config'
import $api from '@/sheep/api';
const showModal = (info = {}) => {
	let _this = this
	let opt = Object.assign({
		title: '温馨提示',
		content: '',
		showCancel: true,
		cancelText: '取消',
		confirmText: '确认',
		confirmColor: '#479EFF'
	}, info)
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: opt.title,
			content: opt.content,
			showCancel: opt.showCancel,
			cancelText: opt.cancelText || '取消',
			confirmText: opt.confirmText || '确定',
			confirmColor: opt.confirmColor,
			success(res) {
				if (res.confirm) {
					return resolve()
				} else if (res.cancel) {
					return reject()
				}
			}
		})
	})
}

/**
 * @description 格式化时间
 * @param {String|Number} dateTime 需要格式化的时间戳
 * @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
 * @returns {string} 返回格式化后的字符串
 */

function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd hh:MM') {
  let date;
  // 若传入时间为假值，则取当前时间
  if (!dateTime) {
    date = new Date();
  }
  // 若为unix秒时间戳，则转为毫秒时间戳（逻辑有点奇怪，但不敢改，以保证历史兼容）
  else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
    date = new Date(dateTime * 1000);
  }
  // 若用户传入字符串格式时间戳，new Date无法解析，需做兼容
  else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
    date = new Date(Number(dateTime));
  }
  // 其他都认为符合 RFC 2822 规范
  else {
    // 处理平台性差异，在Safari/Webkit中，new Date仅支持/作为分割符的字符串时间
    date = new Date(typeof dateTime === 'string' ? dateTime.replace(/-/g, '/') : dateTime);
  }

  const timeSource = {
    y: date.getFullYear().toString(), // 年
    m: (date.getMonth() + 1).toString().padStart(2, '0'), // 月
    d: date.getDate().toString().padStart(2, '0'), // 日
    h: date.getHours().toString().padStart(2, '0'), // 时
    M: date.getMinutes().toString().padStart(2, '0'), // 分
    s: date.getSeconds().toString().padStart(2, '0'), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };

  for (const key in timeSource) {
    const [ret] = new RegExp(`${key}+`).exec(formatStr) || [];
    if (ret) {
      // 年可能只需展示两位
      const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0;
      formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex));
    }
  }

  return formatStr;
}

/**
 * @param {Object} time1
 * @param {Object} time2
 * 计算两个时间的差值
 * @returns {Number} 返回时间差（单位：小时）
 */
function getTimeDifferenceInHours(time1, time2) {
    // 获取当前日期，确保时间使用相同的日期部分
    let currentDate = new Date().toISOString().split('T')[0];  // 获取当前日期（YYYY-MM-DD）

    // 将时间字符串和当前日期组合成完整的时间字符串
    let fullTime1 = currentDate + "T" + time1;
    let fullTime2 = currentDate + "T" + time2;

    // 将时间字符串转换为 Date 对象
    let date1 = new Date(fullTime1);
    let date2 = new Date(fullTime2);

    // 计算时间差（单位为毫秒）
    let timeDifference = date2 - date1;

    // 将毫秒转换为小时
    let hoursDifference = timeDifference / (1000 * 60 * 60);

    // 向上取整，如果是2.6小时则返回3小时
    hoursDifference = Math.ceil(hoursDifference);

    return hoursDifference;
}

function calculateDateTimeRelation(inputDateTime) {
	// 将输入的日期时间字符串转换为Date对象
	const targetDateTime = new Date(convertToSlashFormat(inputDateTime));

	// 获取当前日期时间
	const currentDateTime = new Date();

	// 获取今天、明天和后天的日期
	const today = new Date();
	const tomorrow = new Date();
	tomorrow.setDate(today.getDate() + 1);
	const dayAfterTomorrow = new Date();
	dayAfterTomorrow.setDate(today.getDate() + 2);

	// 比较两个日期时间对象
	if (targetDateTime > currentDateTime) {
		if (isSameDay(targetDateTime, today)) {
			return "今天 " + formatTime(targetDateTime);
		} else if (isSameDay(targetDateTime, tomorrow)) {
			return "明天 " + formatTime(targetDateTime);
		} else if (isSameDay(targetDateTime, dayAfterTomorrow)) {
			return "后天 " + formatTime(targetDateTime);
		} else {
			return formatDateAndTime(targetDateTime);
		}
	} else if (isSameDay(targetDateTime, today)) {
		return "今天 " + formatTime(targetDateTime);
	} else if (isSameDay(targetDateTime, tomorrow)) {
		return "明天 " + formatTime(targetDateTime);
	} else if (isSameDay(targetDateTime, dayAfterTomorrow)) {
		return "后天 " + formatTime(targetDateTime);
	} else {
		return formatDateAndTime(targetDateTime);
	}
}

// 判断两个日期是否是同一天
function isSameDay(date1, date2) {
	return (
		date1.getDate() === date2.getDate() &&
		date1.getMonth() === date2.getMonth() &&
		date1.getFullYear() === date2.getFullYear()
	);
}

// 示例 formatDateAndTime 函数
function formatDateAndTime(dateTime) {
	const year = dateTime.getFullYear();
	const month = (dateTime.getMonth() + 1).toString().padStart(2, '0');
	const day = dateTime.getDate().toString().padStart(2, '0');
	const hours = dateTime.getHours().toString().padStart(2, '0');
	const minutes = dateTime.getMinutes().toString().padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}`;
}

function formatTime(date) {
	// 格式化时间为 HH:mm
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	return hours + ":" + minutes;
}
/**
 * @param {Object} startDate
 * @param {Object} numberOfDays
 * 获取向后n天的日期
 */
function getFutureDates(numberOfDays,startDate = '') {
	const dates = [];
	const currentDate = startDate?new Date(startDate):new Date();
	
	// 星期汉字对照表
	const chineseDaysOfWeek = ['日', '一', '二', '三', '四', '五', '六'];
	for (let i = 0; i < numberOfDays; i++) {
		// 获取当前日期的月份、日期和时间戳
		const year = currentDate.getFullYear();
		const month = currentDate.getMonth() + 1;
		const day = currentDate.getDate();
		const timestamp = currentDate.getTime();
		// 获取当前日期的星期汉字
		const dayOfWeek = chineseDaysOfWeek[currentDate.getDay()];
		// 判断是否是今天
		const todayString = i === 0 ? '今天' : '';
		// 将当前日期信息添加到数组
		dates.push({
			date: `${month}月${day}日`,
			dayOfWeek: todayString + (todayString ? '' : `周${dayOfWeek}`),
			timestamp: timestamp,
			timestampDate: `${year}-${month < 10?'0'+ month:month}-${day < 10?'0'+day:day}`,
			timestampDateIos: `${year}/${month < 10?'0'+ month:month}/${day < 10?'0'+day:day}`,
		});
		// 增加一天
		currentDate.setDate(currentDate.getDate() + 1);
	}
	return dates;
}
/**
 * @description 时间戳转为多久之前
 * @param {String|Number} timestamp 时间戳
 * @param {String|Boolean} format
 * 格式化规则如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
 * @returns {string} 转化后的内容
 */
function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
  if (timestamp == null) timestamp = Number(new Date());
  timestamp = parseInt(timestamp);
  // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
  if (timestamp.toString().length == 10) timestamp *= 1000;
  let timer = new Date().getTime() - timestamp;
  timer = parseInt(timer / 1000);
  // 如果小于5分钟,则返回"刚刚",其他以此类推
  let tips = '';
  switch (true) {
    case timer < 300:
      tips = '刚刚';
      break;
    case timer >= 300 && timer < 3600:
      tips = `${parseInt(timer / 60)}分钟前`;
      break;
    case timer >= 3600 && timer < 86400:
      tips = `${parseInt(timer / 3600)}小时前`;
      break;
    case timer >= 86400 && timer < 2592000:
      tips = `${parseInt(timer / 86400)}天前`;
      break;
    default:
      // 如果format为false，则无论什么时间戳，都显示xx之前
      if (format === false) {
        if (timer >= 2592000 && timer < 365 * 86400) {
          tips = `${parseInt(timer / (86400 * 30))}个月前`;
        } else {
          tips = `${parseInt(timer / (86400 * 365))}年前`;
        }
      } else {
        tips = timeFormat(timestamp, format);
      }
  }
  return tips;
}
function getPreviousNDays(n) {
  const dates = [];
  const today = new Date();
  
  for (let i = 0; i < n; i++) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);
    dates.push(date.toISOString().split('T')[0]); // 格式化为YYYY-MM-DD
  }
  
  return dates.reverse(); // 按时间升序排列
}

/**
 * @param {Object} targetDateString
 * @param {Object} hoursSpan
 * 判断目标时间是否在当前时间的前后n小时之内
 */
function isWithinTimeSpan(targetDateString, hoursSpan = 2) {
    // 将传入的字符串转换为 Date 对象
    const targetDate = new Date(targetDateString);

    // 获取当前时间
    const currentTime = new Date();

    // 计算目标时间与当前时间的差距（以毫秒为单位）
    const timeDifference = Math.abs(currentTime - targetDate);
    
    // 计算给定时间跨度的毫秒数
    const timeSpanInMilliseconds = hoursSpan * 60 * 60 * 1000;

    // 判断差距是否小于给定的时间跨度
    return timeDifference < timeSpanInMilliseconds;
}

function getTimeString(timestamp,times) {
  const now = new Date();
    const targetDate = new Date(timestamp);
    const timeDifference = targetDate.setHours(0, 0, 0, 0) - now.setHours(0, 0, 0, 0);
    const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
    if (timeDifference === 0) {
      return "今天";
    } else if (timeDifference === oneDay) {
      return "明天";
    } else if (timeDifference === 2 * oneDay) {
      return "后天";
    } else {
      // 如果时间戳不是今天、明天或后天，可以返回具体的日期字符串，例如：
      // return targetDate.toLocaleDateString('zh-CN'); // 返回格式化的日期字符串
      return timeFormat(timestamp,'mm-dd');
    }
}
function checkRecentDate(targetDate) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  const yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);
  
  const dayBeforeYesterday = new Date(today);
  dayBeforeYesterday.setDate(today.getDate() - 2);

  targetDate = new Date(targetDate);
  targetDate.setHours(0, 0, 0, 0);

  if (targetDate.getTime() === today.getTime()) {
    return '今天';
  } else if (targetDate.getTime() === yesterday.getTime()) {
    return '昨天';
  } else if (targetDate.getTime() === dayBeforeYesterday.getTime()) {
    return '前天';
  }
  return null;
}
/**
 * 判断会员是否过期
 * 
 * @param {number} expiryTimestamp 会员到期时间的时间戳
 */
function isMembershipExpired(expiryTimestamp = 0) {
    // 获取当前时间的时间戳
    const currentTimestamp = Date.now();
    
    // 判断当前时间是否超过会员到期时间
    return currentTimestamp > expiryTimestamp;
}
/**
 * 获取当前时间
 */
function getCurrentHoursMinutes() {
	const currentDate = new Date();

	// 获取小时和分钟
	const hours = currentDate.getHours();
	const minutes = currentDate.getMinutes();

	// 格式化输出
	const formattedTime = `${hours}:${minutes}`;

	return formattedTime
}

/**
 * @param {string} dateTimeString 当前时间的字符串表示，格式为 'YYYY-MM-DD HH:mm'
 * @param {number} hoursToAdd 要添加的小时数
 * @returns {Object} 包含格式化的当前时间、加上指定小时数后的时间、是否是同一天、是否是次日以及次日的完整日期时间
 */
function getTimelatterTime(dateTimeString, hoursToAdd = 0) {
  // 将初始日期时间字符串转换为 JavaScript Date 对象
     var date = new Date(dateTimeString.replace(/-/g, '/'));
 
     // 添加小时
     date.setHours(date.getHours() + hoursToAdd);
 
     // 获取各个部分的值
     var year = date.getFullYear();
     var month = String(date.getMonth() + 1).padStart(2, '0');
     var day = String(date.getDate()).padStart(2, '0');
     var hours = String(date.getHours()).padStart(2, '0');
     var minutes = String(date.getMinutes()).padStart(2, '0');
 
     // 构建新的日期时间字符串
     var newDateString = `${year}-${month}-${day} ${hours}:${minutes}`;
 
     // 返回新的日期时间字符串
     return newDateString;
}

/**
 * @param {Object} dateString
 * 日期转时间戳
 */
function convertToSlashFormat(dateString) {
	// 使用正则表达式将横线替换为斜线
	if (uni.getSystemInfoSync().platform == 'android') return dateString
	const convertedDate = dateString.replace(/-/g, '/');
	return convertedDate;
}
/**
 * @param {Object} targetDateStr
 * 判断一个日期是否获取
 */
function isDateExpired(targetDateStr) {
	if (!targetDateStr) return true
	// 将目标日期字符串转换为日期对象
	const targetDate = new Date(convertToSlashFormat(targetDateStr));

	// 获取当前日期
	const currentDate = new Date();

	// 比较目标日期和当前日期
	return targetDate < currentDate;
}


function toast(title, mask = false, icon = 'none') {
	uni.showToast({
		title,
		mask,
		icon
	})
}

export async function chooseImage(dataObj = {}, successCallback) {
	let ossInfo = null
	console.log(dataObj);
	uni.chooseImage({
		count: dataObj.count || 1,
		sourceType: dataObj.sourceType || ['album', 'camera'],
		async success(e) {
			if (is_oss_upload) {
				const { code,data } = await $api.common.uploadaccess()
				if(code != 1) return 
				ossInfo = data
			}
			for (var i = 0; i < e.tempFilePaths.length; i++) {
				const imgObj = await uploadFileImg(e.tempFilePaths[i], ossInfo ? ossInfo : null)
				successCallback(imgObj)
			}
		},
		fail(err) {
			console.log(err);
			// uni.showModal({
			// 	title: '消息提示',
			// 	content: err.errMsg,
			// 	showCancel: false
			// })
		}
	})
}
export async function chooseVideo(dataObj = {}, successCallback) {
	let ossInfo = null
	console.log(dataObj);
	uni.chooseVideo({
		count: dataObj.count || 1,
		sourceType: dataObj.sourceType || ['album', 'camera'],
		async success(e) {
			// console.log(e,'ossshujj');
			// console.log(getAddressSuffix(e.tempFilePath));
			// return
			if (is_oss_upload) {
				const { code,data } = await $api.common.uploadaccess()
				if(code != 1) return 
				ossInfo = data
			}
			console.log(e,'ossshujj');
			const imgObj = await uploadFileImg(e.tempFilePath, ossInfo ? ossInfo : null,true)
			successCallback(imgObj)
		},
		fail(err) {
			console.log(err);
			// uni.showModal({
			// 	title: '消息提示',
			// 	content: err.errMsg,
			// 	showCancel: false
			// })
		}
	})
}

/**
 * @name 图片上传
 */
export async function uploadFileImg(file, oss_info, is_video = false) {
	// console.log(oss_info, 'oss详情');
	uni.showLoading({
		title: 'uploading...',
		mask: true
	})
	if (is_oss_upload) {
		if(!oss_info) {
			const { code,data } = await $api.common.uploadaccess()
			if(code != 1) return 
			oss_info = data
		}
		let key = oss_info.key + new Date().getTime() + Math.floor(Math.random() * 100) + (is_video ? '.mp4' : '.png')
		let formData = {
			key: key,
			policy: oss_info.policy,
			OSSAccessKeyId: oss_info.accessid,
			success_action_status: 200,
			signature: oss_info.signature
		};
		return new Promise((resovle, reject) => {
			uni.uploadFile({
				url: oss_info.host,
				filePath: file,
				name: 'file',
				formData: formData,
				header: {
					// #ifdef MP
					"Content-Type": "multipart/form-data",
					// #endif
					"token": uni.getStorageSync('token')
				},
				success: function(res) {
					uni.hideLoading();
					if (res.statusCode == 200) {
						console.log(oss_info.host + '/' + key)
						// successCallback('/' + key)
						resovle({
							url: '/' + key
						})
					} else {
						uni.showToast({
							title: res.errMsg,
							icon: "none"
						})
					}
				},
				fail: function(res) {
					console.log(res);
					uni.hideLoading();
					uni.showToast({
						title: res.errMsg,
						icon: "none"
					})
				}
			})
		})
	} else {
		return new Promise((resovle, reject) => {
			uni.uploadFile({
				url: baseUrl + '/api/uploadfile/uploadImage',
				filePath: file,
				name: 'file',
				header: {
					'token': uni.getStorageSync('token')
				},
				success: (uploadFileRes) => {
					const data = JSON.parse(uploadFileRes.data)
					if (data.code == 1) {
						resovle(data.data)
					} else {
						uni.showModal({
							title: 'Message',
							content: data.msg,
							showCancel: false
						})
						resovle(false)
					}
				},
				fail: err => {
					console.log(err)
					resovle(false)
				},
				complete: () => {
					uni.hideLoading()
				}
			});
		})
	}
}

export function callPhone(phone) {
	uni.makePhoneCall({
		phoneNumber: phone
	})
}

export function copy(content) {
	uni.setClipboardData({
		data: content.toString()
	})
}

export function calculateMinValueByKey(arr, key = 'price') {
	// 使用 reduce 方法找到目标键的最小值
	const minValue = arr.reduce((min, obj) => Math.min(min, obj[key]), Infinity);
	return minValue === Infinity ? undefined : minValue;
}

export function hidePhoneNumber(phoneNumber,visibleDigits = 4) {
	if(!phoneNumber) return
    // 确保输入是字符串
    phoneNumber = String(phoneNumber);

    // 隐藏手机号的中间部分
    var hiddenPart = '*'.repeat(phoneNumber.length - visibleDigits);

    // 构建隐藏后的手机号
    var hiddenPhoneNumber = phoneNumber.substr(0, visibleDigits) + hiddenPart;

    return hiddenPhoneNumber;
}

export const navigation = function({
	address,
	lat,
	lng,
	name
}) {
	if (!lat, !lng) return
	uni.openLocation({
		latitude: Number(lat),
		longitude: Number(lng),
		name,
		address
	})
}
function isImageLink(url) {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'];
  for (let extension of imageExtensions) {
    if (url.endsWith(extension)) {
      return true;  
    }
  }
  return false;
}

async function getCode(){
	// #ifdef MP-WEIXIN
	return new Promise((resovle, reject) => {
		uni.login({
			success: (loginRes) => {
				resovle(loginRes.code)
			},
			fail: (err) => {
				resovle(false)
			}
		})
	})
	// #endif
}

function clone(data){
	return JSON.parse(JSON.stringify(data))
}

function convertToDaysAndHours(totalHours) {
    // 计算天数和剩余的小时数
    const days = Math.floor(totalHours / 24); // 向下取整获取完整天数
    const hours = totalHours % 24; // 取余数获取剩余小时

    // 返回结果
    return `${days}天${hours}小时`;
}
function openKft(kefu_id = 'kfc06ae8a1ab7f757d9',corpId = 'wwc9b88af2362fa4c9'){
	let kefu_ids = kefu_id.split(',') || []
	uni.openCustomerServiceChat({
		extInfo: {
			url: `https://work.weixin.qq.com/kfid/${kefu_ids[getRandomInt(0,kefu_ids.length - 1)]}`
		},
		corpId,
		success(res) {
			console.log(res)
		},
		fail(err) {
			console.log(err)
		}
	})
}

function getRandomInt(min, max) {
	min = Math.ceil(min);
	max = Math.floor(max);
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * 解析参数
 * @param {*} 
 */
 function getQueryVariable(url,variable) {
        var query = url
        console.log(url)
        let params = query.slice(query.indexOf('?')+1)
        var vars =  params.split("&");
        for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) {	
                    return pair[1];
                }
        }
        return (false);
}

function numberToChinese(num) {
  const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const units = ['', '十', '百', '千', '万', '十', '百', '千', '亿'];
  
  if (num === 0) return digits[0];
  let str = '';
  let unitIndex = 0;
  
  while (num > 0) {
    const current = num % 10;
    if (current !== 0) {
      str = digits[current] + units[unitIndex] + str;
    } else if (str.charAt(0) !== '零') {
      str = digits[current] + str;
    }
    num = Math.floor(num / 10);
    unitIndex++;
  }
  
  // 处理"一十"开头的特殊情况
  if (str.startsWith('一十')) {
    str = str.substring(1);
  }
  
  return str.replace(/零+/g, '零').replace(/零$/, '');
}

function toOutLink(url = ''){
	// #ifdef H5
	window.open(url)
	// #endif
	// #ifdef APP
	plus.webview.open(url)
	// #endif
}

function openDocument(url = ''){
	uni.showLoading({
		title: '加载中...'
	})
	uni.downloadFile({
	  url: baseUrl + url,
	  success: function (res) {
	    var filePath = res.tempFilePath;
	    uni.openDocument({
	      filePath: filePath,
	      showMenu: true,
	      success: function (res) {
	        // console.log('打开文档成功');
	      },
		  fail(err) {
		  	toast('打开失败')
		  },
		  complete() {
		  	uni.hideLoading()
		  }
	    });
	  }
	})
}


export default {
	getQueryVariable,
	openKft,
	isWithinTimeSpan,
	convertToDaysAndHours,
	isImageLink,
	isMembershipExpired,
	showModal,
	getFutureDates,
	toast,
	getCode,
	uploadFileImg,
	chooseImage,
	chooseVideo,
	callPhone,
	getCurrentHoursMinutes,
	getTimelatterTime,
	copy,
	convertToSlashFormat,
	calculateMinValueByKey,
	isDateExpired,
	calculateDateTimeRelation,
	navigation,
	hidePhoneNumber,
	getTimeString,
	timeFormat,
	getTimeDifferenceInHours,
	clone,
	getPreviousNDays,
	checkRecentDate,
	numberToChinese,
	toOutLink,
	timeFrom,
	openDocument
}